package cn.tedu.mall.order.controller;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.common.restful.JsonResult;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.order.service.IOmsOrderService;
import cn.tedu.mall.pojo.order.dto.OrderAddDTO;
import cn.tedu.mall.pojo.order.dto.OrderListTimeDTO;
import cn.tedu.mall.pojo.order.vo.OrderAddVO;
import cn.tedu.mall.pojo.order.vo.OrderListVO;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
@RequestMapping("/oms/order")
public class OrderController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private IOmsOrderService orderService;

    /**
     * 新增订单，
     * 1、发送异步消息
     * @param orderAddDTO
     * @return
     */
    @PostMapping("/add")
    @PreAuthorize("hasRole('ROLE_user')")
    public JsonResult<OrderAddVO> orderAdd(OrderAddDTO orderAddDTO) {
        // 生成一个sn（订单编号）
        // 生成sn，需要考虑唯一性，考虑业务数据，还需要考虑高并发，极难
        // 需要通过前端发起Ajax请求，在后端业务中生成sn并返回
        // 这里直接简单处理利用uuid生成一个sn
        String sn = UUID.randomUUID().toString();
        orderAddDTO.setSn(sn);
        // 发送消息
        String msg = JSON.toJSONString(orderAddDTO);
        // 将消息发送到主题，并且绑定一个标签tag=localAdd，因为后面还有秒杀消息tag=secKillAdd
        SendResult result = rocketMQTemplate.syncSend("csmall-order-add-topic:localAdd", msg);
        if (result.getSendStatus().toString().equals("SEND_OK")) {
            // 返回成功
            OrderAddVO orderAddVO = new OrderAddVO();
            orderAddVO.setSn(sn);
            orderAddVO.setPayAmount(orderAddDTO.getAmountOfActualPay());
            return JsonResult.ok(orderAddVO);
        } else {
            throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST, "新增订单失败");
        }
    }

    @GetMapping("/list")
    @PreAuthorize("hasRole('ROLE_user')")
    @ApiOperation(value = "查询当前用户订单列表")
    public JsonResult<JsonPage<OrderListVO>> findMyOrder(OrderListTimeDTO orderListTimeDTO) {
        JsonPage<OrderListVO> orderListVO = orderService.listOrdersBetweenTimes(orderListTimeDTO);
        return JsonResult.ok(orderListVO);
    }
}
